// src/components/core/ProductItem.tsx
import { Button, Card, Col, Image, Row, Typography } from 'antd'
import { push } from 'connected-react-router'
import moment from 'moment'
import React, { FC } from 'react'
import { useDispatch } from 'react-redux'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { addItem } from '../../helpers/cart'
import { Product } from '../../store/models/product'

const { Title, Paragraph } = Typography

interface Props {
    product: Product,
    showViewProduct?: boolean, // 是否显示查看详情
    showCartBtn?: boolean      // 是否显示加入购物车
}

const ProductItem: FC<Props> = ({
    product, 
    showViewProduct = true, 
    showCartBtn = true
}) => {

    const dispatch = useDispatch()

    const addToCart = () => {
        // connected-react-router 模块提供的 push 方法支持使用 dispatch 来实现页面跳转
        addItem(product, () => {
            dispatch(push("/cart"))
        })
    }

    // 控制按钮显示
    const showButtons = () => {
        let buttonArray = []
        if (showViewProduct) {
            buttonArray.push(
                <Button>
                    <Link to={`/product/${product._id}`}>查看详情</Link>
                </Button>
            )
        }
        if (showCartBtn) {
            buttonArray.push(
                <Button type="link" onClick={addToCart}>加入购物车</Button>
            )
        }
        return buttonArray
    }

    return (
        <Card
            hoverable
            cover={
                <Image 
                    src={`${API}/product/photo/${product._id}`} 
                    alt={product.name}
                />
            }
            actions={ showButtons() }
        >
            <Title level={5}>{product.name}</Title>
            <Paragraph ellipsis={{ rows: 2 }}>{product.description}</Paragraph>
            <Row>
                <Col span="12">销量: {product.sold}</Col>
                <Col span="12" style={{textAlign: "right"}}>价格: {product.price}</Col>
            </Row>
            <Row>
                {/* 使用 moment 格式化时间 */}
                <Col span="12">上架时间: {moment(product.createdAt).format('YYYY-MM-DD')}</Col>
                <Col span="12" style={{textAlign: "right"}}>所属分类: {product.category.name}</Col>
            </Row>
        </Card>
    )
}

export default ProductItem